<template>
  <div class="article-list">
    <van-pull-refresh
      v-model="refreshing"
      @refresh="onRefresh"
      :success-text="successText"
      success-duration="1500"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        offset="1"
        :immediate-check="false"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
      >
        <article-cell :Newslist="Newslist.results"></article-cell>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
// 获取新闻列表的api
import { getNewsList } from '@/assets/api/article'

export default {
  name: 'artile-list',
  props: {
    // 新东西
    channel: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      // 下拉组件和列表组件配置项
      loading: false,
      finished: false,
      refreshing: false,
      error: false,
      // 刷新成功的提示数据
      successText: '',
      // 获取新闻推荐列表的请求参数
      queryNewsPramas: {
        channel_id: this.channel.id,
        timestamp: +new Date(),
        with_top: 1
      },
      // 新闻推荐列表
      // 别动这行代码
      Newslist: {
        results: []
      }
    }
  },
  methods: {
    // 注意它执行的必须是异步任务，在mounted之前就会执行
    async onLoad() {
      // 更改新闻推荐列表的请求参数的时间
      const timer = this.Newslist.pre_timestamp
      this.queryNewsPramas.timestamp = timer
      // 发起获取频道新闻推荐_V1.1的请求
      try {
        // 模拟随机错误
        // if (Math.random() > 0.5) {
        //   JSON.parse('asddsads')
        // }
        var { data: res } = await getNewsList(this.queryNewsPramas)
      } catch {
        this.error = true
        // 请求失败了loading也需要关闭
        this.loading = false
        return this.$toast.fail('加载页数据失败')
      }
      // 将数据push到Newslist列表中
      this.Newslist.results.push(...res.data.results)
      this.Newslist.page = res.data.page
      // 改变时间戳
      this.Newslist.pre_timestamp = res.data.pre_timestamp
      // 当返回数据不足10条时判定结束
      if (res.data.results.length === 0) {
        this.finished = true
      }
      this.loading = false
    },
    async onRefresh() {
      try {
        this.queryNewsPramas.timestamp = Date.now()
        var { data: res } = await getNewsList(this.queryNewsPramas)
      } catch {
        this.successText = '刷新失败'
        return (this.refreshing = false)
      }
      // 将数据添加到数组最前面
      this.Newslist.results.unshift(...res.data.results)
      // 提示用户添加成功
      this.successText = `更新成功,更新了${res.data.results.length}条数据`
      this.refreshing = false
    },
    // 获取频道新闻推荐_V1.1
    async getNewsLists() {
      try {
        this.queryNewsPramas.timestamp = +new Date()
        var { data: res } = await getNewsList(this.queryNewsPramas)
      } catch (err) {
        return this.$toast.fail('获取新闻文章列表失败')
      }
      this.Newslist = res.data
    }
  },
  mounted() {
    this.getNewsLists()
  }
}
</script>

<style lang="less" scoped>
.article-list {
  margin-bottom: 100px;
}
</style>
